package backtracking.other;

/**
 * 37. 解数独
 * <p>
 * 编写一个程序，通过填充空格来解决数独问题。
 * <p>
 * 数独的解法需 遵循如下规则：
 * <li>数字1-9在每一行只能出现一次。</li>
 * <li>数字1-9在每一列只能出现一次。</li>
 * <li>数字1-9在每一个以粗实线分隔的3x3宫内只能出现一次</li>
 *
 * <p>
 * <p>
 * 数独部分空格内已填入了数字，空白格用'.'表示。
 */
public class N37_SudokuSolver {
    private boolean backtracking(char[][] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == '.') continue;
                for (char c = '1'; c <= '9'; c++) {
                    if (isValid(i, j, c, board)) {
                        board[i][j] = c;
                        backtracking(board);
                        board[i][j] = '.';
                    }
                }
                return false;
            }
        }
        return true;
    }

    private boolean isValid(int row, int col, char val, char[][] board) {
        // 查行
        for (int i = 0; i < 9; i++)
            if (board[row][i] == val) return false;
        // 查列
        for (int j = 0; j < 9; j++)
            if (board[j][col] == val) return false;
        // 查九宫格
        int startRow = (row / 3) * 3;
        int startCol = (col / 3) * 3;
        for (int i = startRow; i < startRow + 3; i++)
            for (int j = startCol; j < startCol + 3; j++)
                if (board[i][j] == val) return false;
        return true;
    }

    public void solveSudoku(char[][] board) {
        backtracking(board);
    }
}
